package com.lntea.springboot;

public class ThreadMemoryTest {

	public static void main(String[] args) {
		Pair p = new Pair();
		Thread t1 = new Thread(new Thread1(p));
		Thread t2 = new Thread(new Thread2(p));
		t1.start();
		t2.start();
		
		/*while(true){
			if(p.get()%2 == 1){
				System.out.println(Thread.currentThread().getName() + " x:" + p.get());
				throw new RuntimeException();
			}
		}*/
	}
	
}

class Pair{
	Object o1 = new Object();
	Object o2 = new Object();
	int x;
	
	public int get(){
		synchronized(o1){
			return x;
		}
	}
	
	public void incr(){
		synchronized (o2) {
			x++;
			x++;
		}
	}
}

class Thread1 implements Runnable{
	
	Pair p;
	
	public Thread1(Pair p) {
		this.p = p;
	}

	@Override
	public void run() {
		while(true){
			p.incr();
			//System.out.println("x:" + p.get());
		}
	}
	
}

class Thread2 implements Runnable{
	
	Pair p;
	
	public Thread2(Pair p) {
		this.p = p;
	}

	@Override
	public void run() {
		while(true){
			if(p.get()%2 == 1){
				System.out.println(Thread.currentThread().getName() + " x:" + p.get());
				throw new RuntimeException();
			}
		}
	}
	
}
